﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System;
using System.Linq;
using System.Linq.Expressions;
using ex = System.Linq.Expressions;
using ExpressionSerialization;

namespace Demo
{
  public partial class MainPage : UserControl
  {
    public MainPage()
    {
      InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      
      try {
        System.Linq.Expressions.Expression expRoot = null;
        ex.Expression<Func<Demo.Web.Product, bool>> cc;

        //Build Query
        //-- Price --
        if(!string.IsNullOrEmpty(txtPrice1.Text)) {
          cc = p => p.ListPrice >= decimal.Parse(txtPrice1.Text);
          expRoot = expRoot.LogicalAnd(cc);
        }
        if(!string.IsNullOrEmpty(txtPrice2.Text)) {
          cc = p => p.ListPrice <= decimal.Parse(txtPrice2.Text);
          expRoot = expRoot.LogicalAnd(cc);
        }
        //Size
        if(!string.IsNullOrEmpty(txtSize1.Text)) {
          cc = p => p.Size >= decimal.Parse(txtSize1.Text);
          expRoot = expRoot.LogicalAnd(cc);
        }
        if(!string.IsNullOrEmpty(txtSize2.Text)) {
          cc = p => p.Size <= decimal.Parse(txtSize2.Text);
          expRoot = expRoot.LogicalAnd(cc);
        }
        //Colors
        string[] bikeColors = new String[] { txtColor1.Text, txtColor2.Text, txtColor3.Text };
        ex.Expression expColor = null;
        foreach(var item in bikeColors) {
          if(!string.IsNullOrEmpty(item)) {
            string ss = item.ToUpper();
            cc = p => p.Color.ToUpper().Contains(ss);
            expColor = expColor.LogicalOr(cc);
          }
        }
        expRoot = expRoot.LogicalAnd(expColor);

        byte[] query = null;
        if(expRoot != null) {
          query = expRoot.Serialize();
        }

        dsProducts.QueryParameters[0].Value = query;
        dsProducts.Load();
      } catch {
        MessageBox.Show("Invalid Input");
      }
      
    }

  }
}
